package com.good.child.widgets.editext;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatEditText;

import com.good.child.R;

/**
 * Create on: 2024/2/27
 * by Mr.Zhu
 * Description: TODO
 */
public class DigitsEditText extends AppCompatEditText {
    int pointLeftLength = Integer.MAX_VALUE;
    int pointRightLength = 2;
    private DecimalFilter moneyValueFilter;

    public DigitsEditText(Context context) {
        this(context, null);
    }

    public DigitsEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public DigitsEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.InputEditView);
            if (typedArray.hasValue(R.styleable.InputEditView_pointLeftLength)) {
                pointLeftLength = typedArray.getInt(R.styleable.InputEditView_pointLeftLength, Integer.MAX_VALUE);
                pointRightLength = typedArray.getInt(R.styleable.InputEditView_pointRightLength, 2);
                setFilter();
            }
        }
        // setGravity(Gravity.CENTER);
    }

    public void setPointLeftLength(int pointLeftLength) {
        this.pointLeftLength = pointLeftLength;
        setFilter();
    }

    public void setPointRightLength(int pointRightLength) {
        this.pointRightLength = pointRightLength;
        setFilter();
    }

    @Override
    public void setFilters(InputFilter[] filters) {
        InputFilter[] oldFilters = getFilters();
        if (oldFilters != null && oldFilters.length > 0) {
            InputFilter[] temp = new InputFilter[filters.length + oldFilters.length];//7
            System.arraycopy(oldFilters, 0, temp, 0, oldFilters.length);//3 temp ==3
            System.arraycopy(filters, 0, temp, oldFilters.length, filters.length);//4
            filters = temp;
        }
        super.setFilters(filters);
    }

    private void setFilter() {
        if (moneyValueFilter == null) {
            moneyValueFilter = new DecimalFilter(pointLeftLength, pointRightLength);
            setFilters(new InputFilter[]{moneyValueFilter});
        } else {
            moneyValueFilter.setPointerLeftLength(pointLeftLength);
            moneyValueFilter.setPointerRightLength(pointRightLength);
        }
    }

    public void setPointLength(int pointLeftLength, int pointRightLength) {
        this.pointLeftLength = pointLeftLength;
        this.pointRightLength = pointRightLength;
        setFilter();
    }

    public boolean isInputDecimal() {
        return pointRightLength > 0;
    }
}
